import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import router from 'umi/router';
import { message } from 'antd';

import { fetchValidation } from '@/utils';
import {
  queryFranchiseeDetail,
  queryFranchiseeList,
  queryGardensByPhone,
  queryGardensByName,
  saveFranchisee,
} from './service';


export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: {}) => T) => T }
) => void;

export interface ModelType {
  namespace: string;
  state: {};
  effects: {
    fetch: Effect;
    fetchFranchisees: Effect;
    fetchGardensByPhone: Effect;
    fetchGardensByName: Effect;
    save: Effect;
  };
  reducers: {
    show: Reducer;
    import: Reducer;
    saveGardens: Reducer;
    franchisees: Reducer;
    clean: Reducer;
  };
}

const defaultData = {
  detail: {},
  parentList: [],
  importGardenList: [],
  gardenList: [],
};

const Model: ModelType = {
  namespace: 'partnerFranchiseeEdit',

  state: defaultData,

  effects: {
    * fetch({ payload }, { call, put }) {
      const response = yield call(queryFranchiseeDetail, payload);
      const data = fetchValidation(response);
      yield data && put({
        type: 'show',
        payload: response.body,
      });
    },
    * fetchFranchisees({ payload }, { call, put }) {
      const response = yield call(queryFranchiseeList, payload);
      const data = fetchValidation(response);
      yield data && put({
        type: 'franchisees',
        payload: response.body,
      });
    },
    * fetchGardensByPhone({ payload }, { call, put }) {
      const response = yield call(queryGardensByPhone, payload);
      const data = fetchValidation(response);
      yield data && put({
        type: 'import',
        payload: response.body,
      });
    },
    * fetchGardensByName({ payload }, { call, put }) {
      const response = yield call(queryGardensByName, payload);
      const data = fetchValidation(response);
      yield data && put({
        type: 'saveGardens',
        payload: response.body.data_list,
      });
    },
    * save({ payload }, { call, put }) {
      const response = yield call(saveFranchisee, payload);
      const data = fetchValidation(response);
      if (data) {
        message.success('提交成功');
        yield put({
          type: 'global/setPath',
        });
        router.push('/partner/franchisee/list');
      }
    },
  },

  reducers: {
    show(state, { payload }) {
      return {
        ...state,
        detail: payload,
      };
    },
    import(state, { payload }) {
      return {
        ...state,
        importGardenList: payload,
      };
    },
    franchisees(state, { payload }) {
      return {
        ...state,
        parentList: payload,
      };
    },
    saveGardens(state, { payload }) {
      return {
        ...state,
        gardenList: payload,
      };
    },
    clean() {
      return defaultData;
    },
  },
};

export default Model;
